#!/usr/bin/env python
# -*- coding: utf-8 -*-

from utils import log
from sqlalchemy.orm import mapper, sessionmaker
from datetime import datetime
from sqlalchemy import Table, MetaData, Column, ForeignKey, Integer, BigInteger, String, Unicode, UnicodeText, DateTime
from controls.data_pool_mysql import engine

# 创建到数据库的连接,echo=True表示用logging输出调试结果
metadata = MetaData()
Session = sessionmaker()  # 创建了一个自定义了的 Session类
Session.configure(bind=engine)  # 将创建的数据库连接关联到这个session

"""user_reset collection has
   rid:        唯一标识串 (str)
   email:      email (str)
   phone:      phone (str)
   rtime:      reset时间 (datatime)
"""


class UserResetItem(object):  # 创建一个映射类

    def to_dict(self):
        res = {}
        res['uid'] = self.uid
        res['phone'] = self.phone
        # res['email'] = self.email
        res['rtime'] = self.rtime
        return res

    def __repr__(self):
        return "%d" % (self.uid)


user_reset_table = Table(
    'user_reset', metadata,
    Column('id', Integer, primary_key=True),
    Column('rid', Integer, index=True, nullable=False),
    Column('phone', Unicode(65), index=True, default=''),
    # Column('email', Unicode(65), index=True, default=''),
    Column('rtime', DateTime, default=datetime.now, nullable=False),
)

mapper(UserResetItem, user_reset_table)  # 把表映射到类


def create_user_reset_table_if_not_exist():
    metadata.create_all(engine)  # 在数据库中生成表


def add_user_reset_item(p_item):
    try:
        session = Session()
        session.add(p_item)  # 往session中添加内容
        session.flush()  # 保存数据
        session.commit()  # 数据库事务的提交,sisson自动过期而不需要关闭
        return True
    except Exception as e:
        log.exp(e)
        session.rollback()
        return False
    finally:
        session.close()
        # session.remove()


def get_user_reset(p_rid):
    try:
        session = Session()
        query = session.query(UserResetItem)
        item = query.filter_by(urlid=p_rid).first()
        return item
    except Exception as e:
        log.exp(e)
        return None
    finally:
        session.close()
        # session.remove()


# def del_user_reset(p_email):
#     try:
#         session = Session()
#         query = session.query(UserResetItem)
#         query.filter_by(email=p_email).delete()
#         session.flush()  # 保存数据
#         session.commit()  # 数据库事务的提交,sisson自动过期而不需要关闭
#         return True
#     except Exception as e:
#         log.exp(e)
#         session.rollback()
#         return False
#     finally:
#         session.close()
#         # session.remove()
if __name__ == "__main__":
    create_user_reset_table_if_not_exist()